﻿using Ewell.BizComponent.Charge.Model;
using Ewell.BizComponent.Service.Model.Dto;
using Ewell.BizComponent.Service.Model.Response;
using Ewell.BizComponent.Service.Server;
using Ewell.Interface.Common.Model.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using System.Windows;
using Ewell.BizComponent.Service.Model.Request;
using Ewell.Interface.Accounting.Common.Model.Request;
using Ewell.Interface.Common.Model.GateWay.Dto.Dict;
using Ewell.Interface.Common.Model.GateWay.GateWayUriInfo;
using Ewell.Interface.Common.Utils;
using Newtonsoft.Json;
using Ewell.BizComponent.Service.Model.Insur.Response;
using Ewell.Interface.Accounting.Common.Model.Response;
using OutPayResponse = Ewell.BizComponent.Service.Model.Insur.Response.OutPayResponse;
using Ewell.BizComponent.Service.Model.Constant;
using Ewell.Interface.Accounting.Common.Model.Constant;
using Ewell.BizComponent.Service.Model.Invoice.Request;

namespace Ewell.BizComponent.Charge.UI.VM
{
    public class CashierNewVm:CashierBaseVm
    {
        public CashierNewVm() { }
        public CashierNewVm(ChargingInfoVm chargingInfo) : this()
        {
            this.chargingInfo = chargingInfo;
        }
        public CashierNewVm(ChargingInfoVm chargingInfo, List<PayWayVm> payWayList) : this(chargingInfo)
        {
            this.payWayList = payWayList;
            this.prestorePayWay = this.payWayList.FirstOrDefault(f => f.no == "HIS001");
            this.otherPayWayList = this.payWayList.Where(f => f.no != "HIS001").ToList();
        }
        /// <summary>
        /// 当前窗体
        /// </summary>
        public Window localWindow { get; set; }
        /// <summary>
        /// 支付方式
        /// </summary>
        private List<PayWayVm> _payWayList;
        public List<PayWayVm> payWayList
        {
            get => _payWayList; set
            {
                if (value != _payWayList)
                {
                    _payWayList = value;
                    OnPropertyChanged(nameof(payWayList));
                }
            }
        }
        /// <summary>
        /// 预存账户支付方式
        /// </summary>
        private PayWayVm _prestorePayWay;
        public PayWayVm prestorePayWay
        {
            get => _prestorePayWay;
            set
            {
                if (value != _prestorePayWay)
                {
                    _prestorePayWay = value;
                    OnPropertyChanged(nameof(prestorePayWay));
                }
            }
        }
        /// <summary>
        /// 预存账户之外的支付方式
        /// </summary>
        public List<PayWayVm> _otherPayWayList;
        public List<PayWayVm> otherPayWayList
        {
            get => _otherPayWayList; set
            {
                if (value != _otherPayWayList)
                {
                    _otherPayWayList = value;
                    OnPropertyChanged(nameof(otherPayWayList));
                }
            }
        }
        /// <summary>
        /// 单支付方式下选中的支付方式
        /// </summary>
        private PayWayVm _selectPayWay;
        public PayWayVm selectPayWay
        {
            get => _selectPayWay;
            set
            {
                if (value != _selectPayWay)
                {
                    _selectPayWay = value;
                    OnPropertyChanged(nameof(selectPayWay));
                }
            }
        }
        /// <summary>
        /// 患者信息
        /// </summary>
        private PatientVm _patientVm;
        public PatientVm patientVm
        {
            get => _patientVm; set
            {
                if (value != _patientVm)
                {
                    _patientVm = value;
                    OnPropertyChanged(nameof(patientVm));
                }
            }
        }
        /// <summary>
        /// 收费信息
        /// </summary>
        private ChargingInfoVm _chargingInfo;
        public ChargingInfoVm chargingInfo
        {
            get => _chargingInfo; set
            {
                if (_chargingInfo != value)
                {
                    _chargingInfo = value;
                    OnPropertyChanged(nameof(chargingInfo));
                }
            }
        }
        /// <summary>
        /// 收费结果通知
        /// </summary>
        public event EventHandler<CashierContext> NoticeChargeResult;
        /// <summary>
        /// 取消收费通知
        /// </summary>
        public event EventHandler<CashierContext> NoticeChargeCancel;

        /// <summary>
        /// 结算事件
        /// </summary>
        public ICommand settlement => new RelayCommand((object param) =>
        {
            this.context.cashierMainVm.next();
        });
        /// <summary>
        /// 取消结算
        /// </summary>
        public ICommand settlementCancel => new RelayCommand((object param) =>
        {
            var onlinePayList = payWayList.Where(x => x.interfaceId.HasValue && x.paySuccess == true)?.ToList();
            if (onlinePayList.Count > 0)
            {
                OnlinePayVm onlinePayVm = new OnlinePayVm()
                {
                    patientVm = this.patientVm,
                    chargingInfo = this.chargingInfo,
                    payWayList = onlinePayList,
                };
                OnlinePayFrm onlinePayFrm = new OnlinePayFrm(onlinePayVm);
                onlinePayFrm.Owner = this.localWindow;
                onlinePayVm.localWindows = onlinePayFrm;
                onlinePayFrm.RefundAll();
            }

            if (payWayList.Any(a => a.interfaceId.HasValue && a.paySuccess == true))
            {
                MessageBox.Show("还有未退费的支付金额！");
                return;
            }
            InsurServer insurServer = new InsurServer();
            if (this.context.outPreSettlementRequest.settlementTypeCode == "1" && !string.IsNullOrWhiteSpace(this.context.patientVm.interfaceId))
            {
                insurServer.cancelOutRegisterPreview(new RequestHeader() { interfaceId = long.Parse(this.context.patientVm.interfaceId), alreadySelectDataList = this.context.alreadySelectDataList }, new OutRegisterCancelPreviewRequest() { outPayMtNo = this.context.outPreSettlementResponse.settlementId.ToString(), patientId = this.context.patientVm.patientId, visitNo = this.context.outPreSettlementRequest.encounter.encounterId.ToString() });
            }
            else if(this.context.outPreSettlementRequest.settlementTypeCode == "2" && !string.IsNullOrWhiteSpace(this.context.patientVm.interfaceId))
            {
                insurServer.cancelOutPayPreview(new RequestHeader() { interfaceId = long.Parse(this.context.patientVm.interfaceId), alreadySelectDataList = this.context.alreadySelectDataList }, new OutPayCancelPreviewRequest() { outPayMtNo = this.context.outPreSettlementResponse.settlementId.ToString(), patientId = this.context.patientVm.patientId, visitNo = this.context.outPreSettlementRequest.encounter.encounterId.ToString() });
            }
            this.context.chargingInfo.insurAmount = null;
            NoticeChargeCancel?.Invoke(this, this.context);
        });
        /// <summary>
        /// 支付失败重试
        /// </summary>
        public ICommand rePay => new RelayCommand((object payWay) =>
        {
            PayWayVm payWayVm = payWay as PayWayVm;
            //this.Pay(payWayVm);
            var rePayWayList = this.payWayList.Where(w => w.no == payWayVm.no).ToList();
            rePayWayList.ForEach(x => x.payQrCode = string.Empty);
            OnlinePayVm onlinePayVm = new OnlinePayVm()
            {
                patientVm = this.patientVm,
                chargingInfo = this.chargingInfo,
                payWayList = rePayWayList,
            };
            OnlinePayFrm onlinePayFrm = new OnlinePayFrm(onlinePayVm);
            onlinePayFrm.Owner = this.localWindow;
            onlinePayVm.localWindows = onlinePayFrm;
            onlinePayFrm.PayAll();
        });

        public override CashierStepVm.StepLoading stepLoading => new CashierStepVm.StepLoading(context =>
        {
            this.context = context;
            this.payWayList = context.cashierMainVm.payWayList;
            this.prestorePayWay = this.payWayList.FirstOrDefault(f => f.no == "HIS001");
            this.otherPayWayList = this.payWayList.Where(f => f.no != "HIS001").ToList();
            this.patientVm = context.patientVm;
            this.chargingInfo = context.chargingInfo;
            context.cashierMainVm.currentStep.StepState = FunnyArts.Wpf.ControlLibrary.Model.StepStatus.Running;

            CashierVm cashierVm = new CashierVm(this.chargingInfo, this.payWayList);
            cashierVm.patientVm = this.patientVm;
            this.framePage = new CashierFrm(cashierVm);

            context.cashierMainVm.currentStep.page = new CashierNewFrm();
            context.cashierMainVm.currentStep.page.DataContext = this;


            if (string.IsNullOrEmpty(context.patientVm.interfaceId)) return;
            InsurServer insurServer = new InsurServer();
            //查询医保是否需要读卡
            NeedReadCardResponse needReadCardResponse = insurServer.GetNeedReadCard(new RequestHeader() { interfaceId = long.Parse(context.patientVm.interfaceId) }, new NeedReadCardRequest()
            {
                currentBizTransactionCoding = context.outPreSettlementRequest.settlementTypeCode == "1" ? "103" : "203",
                patientId = context.patientVm.interfaceId,
                payMtNo = context.chargingInfo.settlementId.ToString(),
                visitNo = context.chargingInfo.encounterId.ToString(),
            });

            if (needReadCardResponse != null && needReadCardResponse.needReadCardStatus is "1" or "2")
            {
                QueryBizSearchComponentListReq req = new QueryBizSearchComponentListReq()
                {
                    componentCoding = "6",
                    enabledFlag = "1",
                };
                BizSearchComponentDubboService bizSearchComponentDubboService = new BizSearchComponentDubboService();
                var gateWayResult = bizSearchComponentDubboService.queryBizSearchComponentListByCoding.Post<QueryBizSearchComponentListResp>(req).CheckState();
                if (gateWayResult.@object?.bizSearchTypeList?.Count == 0)
                    throw new SpeedException("读卡组件设置错误!");
                List<ButtonComponentVm> buttonComponents = new List<ButtonComponentVm>();
                foreach (var item in gateWayResult.@object.bizSearchTypeList)
                {
                    buttonComponents.Add(item.CopyProperties<ButtonComponentVm>());
                }
                SearchComponentVm searchComponentVm = new SearchComponentVm();
                searchComponentVm.context = context;
                searchComponentVm.buttonComponents = buttonComponents;
                searchComponentVm.currBizTradeCode = context.outPreSettlementRequest.settlementTypeCode == "1" ? "103" : "203";
                readCardPage = new SearchComponentFrm(searchComponentVm);
                this.framePage = readCardPage;
                return;
            }
        });

        public override CashierStepVm.StepHandler stepHandler => new CashierStepVm.StepHandler(context =>
        {
            
        });

        public ICommand stepContinue => new RelayCommand(context =>
        {
            if (this.framePage == readCardPage)
            {
                string currentBizParams = this.context.outPreSettlementRequest.settlementTypeCode == "1" ? JsonConvert.SerializeObject(new OutRegisterPreviewRequest() { outPayMtNo = this.context.outPreSettlementResponse.settlementId.ToString(), patientId = this.context.patientVm.patientId, visitNo = this.context.outPreSettlementRequest.encounter.encounterId.ToString() }) : JsonConvert.SerializeObject(new OutPayPreviewRequest() { outPayMtNo = this.context.outPreSettlementResponse.settlementId.ToString(), patientId = this.context.patientVm.patientId, visitNo = this.context.outPreSettlementRequest.encounter.encounterId.ToString() });
                InsurServer insurServer = new InsurServer();
                List<DataSelectItemResponse> dataSelectItemResponses = insurServer.InitDataSelectItem(new RequestHeader() { interfaceId = long.Parse(this.context.patientVm.interfaceId), cardInfo = this.context.basicInfo, alreadySelectDataList = this.context.alreadySelectDataList }, new DataSelectItemInitRequest()
                {
                    currentBizParams = currentBizParams,
                    currentBizTransactionCoding = this.context.outPreSettlementRequest.settlementTypeCode == "1" ? "101" : "201",
                });

                if (dataSelectItemResponses != null && dataSelectItemResponses.Count > 0)
                {
                    dataSelectPage = new DataSelectFrm();
                    this.framePage = dataSelectPage;
                    return;
                }
            }
            if (this.framePage == dataSelectPage)
            {
                var dataSelectVm = (dataSelectPage as DataSelectFrm).vm;
                if (dataSelectVm.dataSelectItemList != null && dataSelectVm.dataSelectItemList.Count > 0)
                {
                    this.context.alreadySelectDataList = new List<DataSelectRequest>();
                    foreach (var item in dataSelectVm.dataSelectItemList)
                    {
                        this.context.alreadySelectDataList.Add(new DataSelectRequest()
                        {
                            basicDataDictTypeId = item.basicDataDictTypeId,
                            basicDataDictTypeNo = item.basicDataDictTypeNo,
                            basicDataId = item.basicDataId,
                            basicDataNo = item.basicDataNo,
                            basicDataName = item.basicDataName,
                        });
                    }
                }
            }
            this.context.chargeResult = new ChargeResultVm()
            {
                success = false,
                settlementId = chargingInfo.settlementId,
                recAmount=chargingInfo.recAmount
            };

            //校验
            if (payWayList.Where(w => w.amount > 0).Sum(w => w.amount) != this.chargingInfo.recAmount)
            {
                MessageBox.Show("支付金额不等于应收金额!");
                return;
            }
            var onlinePayList = payWayList.Where(x => x.interfaceId.HasValue && x.amount > 0 && x.paySuccess != true)?.ToList();
            if (onlinePayList.Count > 0)
            {
                onlinePayList.ForEach(x => x.payQrCode = string.Empty);
                OnlinePayVm onlinePayVm = new OnlinePayVm()
                {
                    patientVm = this.patientVm,
                    chargingInfo = this.chargingInfo,
                    payWayList = onlinePayList,
                };
                OnlinePayFrm onlinePayFrm = new OnlinePayFrm(onlinePayVm);
                onlinePayFrm.Owner = this.localWindow;
                onlinePayVm.localWindows = onlinePayFrm;
                onlinePayFrm.PayAll();
            }

            if (payWayList.Any(a => a.interfaceId.HasValue && a.amount > 0 && a.paySuccess != true))
            {
                var payWayFail = payWayList.FirstOrDefault(f => f.interfaceId.HasValue && f.amount > 0 && f.paySuccess != true);
                MessageBox.Show($"支付方式【{payWayFail.name}】支付金额【{payWayFail.amount}】失败！请重试!");
                return;
            }
            //医保结算
            try
            {
                if (this.context.outPreSettlementRequest.settlementTypeCode == "1" && !string.IsNullOrWhiteSpace(this.context.patientVm.interfaceId))
                {
                    InsurServer insurServer = new InsurServer();
                    var response = insurServer.beforeOutRegister(new RequestHeader() { interfaceId = long.Parse(this.context.patientVm.interfaceId), alreadySelectDataList = this.context.alreadySelectDataList }, new OutRegisterBeforeRequest() { outPayMtNo = this.context.outPreSettlementResponse.settlementId.ToString(), patientId = this.context.patientVm.patientId, visitNo = this.context.outPreSettlementRequest.encounter.encounterId.ToString() });
                    this.context.outPayResponse = response.CopyProperties<OutPayResponse>();
                    this.context.chargingInfo.insurAmount = response.insurReimAmount;
                }
                else if(this.context.outPreSettlementRequest.settlementTypeCode == "2" && !string.IsNullOrWhiteSpace(this.context.patientVm.interfaceId))
                {
                    InsurServer insurServer = new InsurServer();
                    var response = insurServer.beforeOutPay(new RequestHeader() { interfaceId = long.Parse(this.context.patientVm.interfaceId), alreadySelectDataList = this.context.alreadySelectDataList }, new OutPayBeforeRequest() { outPayMtNo = this.context.outPreSettlementResponse.settlementId.ToString(), patientId = this.context.patientVm.patientId, visitNo = this.context.outPreSettlementRequest.encounter.encounterId.ToString() });
                    this.context.outPayResponse = response;
                    this.context.chargingInfo.insurAmount = response.insurReimAmount;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("医保结算失败!" + ex.Message);
                return;
            }
            //结算
            List<PayRecordDto> payRecords = new List<PayRecordDto>();
            foreach (var payWay in payWayList.Where(w => w.amount > 0 && ((w.interfaceId.HasValue && w.paySuccess == true) || !w.interfaceId.HasValue)))
            {
                PayRecordDto payRecordDto = new PayRecordDto()
                {
                    payAmount = payWay.amount,
                    payWayId = payWay.no,
                    thirdPartTranId = payWay.payTxnNo,
                };
                payRecords.Add(payRecordDto);
            }

            OutSettlementRequest settlementRequest = new OutSettlementRequest()
            {
                settlementInfo = new SettlementDto()
                {
                    settlementId = chargingInfo.settlementId.ToString(),
                    payTypeCoding = chargingInfo.settlementTypeCode,
                    amount = chargingInfo.amount.Value,
                    discountAmount = chargingInfo.discountAmount.Value,
                    insurAmount = chargingInfo.insurAmount ?? 0,
                    selfPayAmount = chargingInfo.recAmount.Value,
                    payRecordList = payRecords,
                }
            };
            OutSettlementServer outSettlementServer = new OutSettlementServer();
            try
            {
                OutSettlementResponse response = outSettlementServer.Settlement(settlementRequest);
            }
            catch (SpeedException ex)
            {
                MessageBox.Show($"收费失败!,{ex.Message}");
                //退支付
                if (payWayList.Any(a => a.interfaceId.HasValue && a.amount > 0 && a.paySuccess == true))
                {
                    OnlinePayVm onlinePayVm = new OnlinePayVm()
                    {
                        patientVm = this.patientVm,
                        chargingInfo = this.chargingInfo,
                        payWayList = payWayList.Where(a => a.interfaceId.HasValue && a.amount > 0 && a.paySuccess == true).ToList(),
                    };
                    OnlinePayFrm onlinePayFrm = new OnlinePayFrm(onlinePayVm);
                    onlinePayFrm.Owner = this.localWindow;
                    onlinePayVm.localWindows = onlinePayFrm;
                    onlinePayFrm.RefundAll();
                }
                //医保正算失败后
                try
                {
                    if (this.context.outPreSettlementRequest.settlementTypeCode == "1" && !string.IsNullOrWhiteSpace(this.context.patientVm.interfaceId))
                    {
                        InsurServer insurServer = new InsurServer();
                        insurServer.failOutRegister(new RequestHeader() { interfaceId = long.Parse(this.context.patientVm.interfaceId), alreadySelectDataList = this.context.alreadySelectDataList }, new OutRegisterFailRequest() { outPayMtNo = this.context.outPreSettlementResponse.settlementId.ToString(), patientId = this.context.patientVm.patientId, visitNo = this.context.outPreSettlementRequest.encounter.encounterId.ToString() });
                    }
                    else if (this.context.outPreSettlementRequest.settlementTypeCode == "2" && !string.IsNullOrWhiteSpace(this.context.patientVm.interfaceId))
                    {
                        InsurServer insurServer = new InsurServer();
                        insurServer.failOutPay(new RequestHeader() { interfaceId = long.Parse(this.context.patientVm.interfaceId), alreadySelectDataList = this.context.alreadySelectDataList }, new OutPayFailRequest() { outPayMtNo = this.context.outPreSettlementResponse.settlementId.ToString(), patientId = this.context.patientVm.patientId, visitNo = this.context.outPreSettlementRequest.encounter.encounterId.ToString() });
                    }
                }
                catch (Exception exc)
                {
                    MessageBox.Show("撤销医保失败!"+ exc.Message);
                    return;
                }
                return;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"收费失败!,{ex.Message}");
                //退支付
                if (payWayList.Any(a => a.interfaceId.HasValue && a.amount > 0 && a.paySuccess == true))
                {
                    OnlinePayVm onlinePayVm = new OnlinePayVm()
                    {
                        patientVm = this.patientVm,
                        chargingInfo = this.chargingInfo,
                        payWayList = payWayList.Where(a => a.interfaceId.HasValue && a.amount > 0 && a.paySuccess == true).ToList(),
                    };
                    OnlinePayFrm onlinePayFrm = new OnlinePayFrm(onlinePayVm);
                    onlinePayFrm.Owner = this.localWindow;
                    onlinePayVm.localWindows = onlinePayFrm;
                    onlinePayFrm.RefundAll();
                }
                //医保正算失败后
                try
                {
                    if (this.context.outPreSettlementRequest.settlementTypeCode == "1" && !string.IsNullOrWhiteSpace(this.context.patientVm.interfaceId))
                    {
                        InsurServer insurServer = new InsurServer();
                        insurServer.failOutRegister(new RequestHeader() { interfaceId = long.Parse(this.context.patientVm.interfaceId), alreadySelectDataList = this.context.alreadySelectDataList }, new OutRegisterFailRequest() { outPayMtNo = this.context.outPreSettlementResponse.settlementId.ToString(), patientId = this.context.patientVm.patientId, visitNo = this.context.outPreSettlementRequest.encounter.encounterId.ToString() });
                    }
                    else if (this.context.outPreSettlementRequest.settlementTypeCode == "2" && !string.IsNullOrWhiteSpace(this.context.patientVm.interfaceId))
                    {
                        InsurServer insurServer = new InsurServer();
                        insurServer.failOutPay(new RequestHeader() { interfaceId = long.Parse(this.context.patientVm.interfaceId), alreadySelectDataList = this.context.alreadySelectDataList }, new OutPayFailRequest() { outPayMtNo = this.context.outPreSettlementResponse.settlementId.ToString(), patientId = this.context.patientVm.patientId, visitNo = this.context.outPreSettlementRequest.encounter.encounterId.ToString() });
                    }
                }
                catch (Exception exc)
                {
                    MessageBox.Show("医保撤销失败!" + exc.Message);
                    return;
                }
                
                return;
            }
            //医保正算后
            try
            {
                if (this.context.outPreSettlementRequest.settlementTypeCode == "1" && !string.IsNullOrWhiteSpace(this.context.patientVm.interfaceId))
                {
                    InsurServer insur = new InsurServer();
                    insur.afterOutRegister(new RequestHeader() { interfaceId = long.Parse(this.context.patientVm.interfaceId), alreadySelectDataList = this.context.alreadySelectDataList }, new OutRegisterAfterRequest() { outPayMtNo = this.context.outPreSettlementResponse.settlementId.ToString(), patientId = this.context.patientVm.patientId, visitNo = this.context.outPreSettlementRequest.encounter.encounterId.ToString() });
                }
                else if (this.context.outPreSettlementRequest.settlementTypeCode == "2" && !string.IsNullOrWhiteSpace(this.context.patientVm.interfaceId))
                {
                    InsurServer insur = new InsurServer();
                    insur.afterOutPay(new RequestHeader() { interfaceId = long.Parse(this.context.patientVm.interfaceId), alreadySelectDataList = this.context.alreadySelectDataList }, new OutPayAfterRequest() { outPayMtNo = this.context.outPreSettlementResponse.settlementId.ToString(), patientId = this.context.patientVm.patientId, visitNo = this.context.outPreSettlementRequest.encounter.encounterId.ToString() });
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("执行医保结算后处理异常:"+ex.Message);
            }

            //电子发票
            try
            {
                List<string> formCodes= new List<string>();
                if (this.context.outPreSettlementRequest.settlementTypeCode == "1")
                    formCodes.Add(FormCoding.R_O_009_E.code);
                else
                    formCodes.Add(FormCoding.R_O_008_E.code);
                FormPrintManagementDubboService formPrintManagementDubboService = new FormPrintManagementDubboService();
                var gateWayResult=formPrintManagementDubboService.queryFormInfoByFormCodes.Post<List<FormPrintResp>>(formCodes).CheckState();

                if(gateWayResult.@object!=null&& gateWayResult.@object.Count>0)
                {
                    var formPrintResp=gateWayResult.@object[0];
                    FormPrint(this.context, formPrintResp);
                }
            }
            catch (Exception ex)
            {
                LogHelper.Debug(ex.Message);
            }
            
            this.context.chargeResult.success = true;
            this.context.cashierMainVm.next();
            NoticeChargeResult?.Invoke(this, this.context);
        });

        public ICommand stepCancel => new RelayCommand(context =>
        {
            if (payWayList.Any(a => a.interfaceId.HasValue && a.amount > 0 && a.paySuccess == true))
            {
                OnlinePayVm onlinePayVm = new OnlinePayVm()
                {
                    patientVm = this.patientVm,
                    chargingInfo = this.chargingInfo,
                    payWayList = payWayList.Where(a => a.interfaceId.HasValue && a.amount > 0 && a.paySuccess == true).ToList(),
                };
                OnlinePayFrm onlinePayFrm = new OnlinePayFrm(onlinePayVm);
                onlinePayFrm.Owner = this.localWindow;
                onlinePayVm.localWindows = onlinePayFrm;
                onlinePayFrm.RefundAll();
            }
            //医保正算取消
            if (this.context.outPayResponse!=null)
            {
                InsurServer insurServer = new InsurServer();
                if (this.context.outPreSettlementRequest.settlementTypeCode == "1")
                {
                    insurServer.failOutPay(new RequestHeader() { interfaceId = long.Parse(this.context.patientVm.interfaceId), alreadySelectDataList = this.context.alreadySelectDataList }, new OutPayFailRequest() { outPayMtNo = this.context.outPreSettlementResponse.settlementId.ToString(), patientId = this.context.patientVm.patientId, visitNo = this.context.outPreSettlementRequest.encounter.encounterId.ToString() });
                    this.context.chargingInfo.insurAmount = null;
                }
                else
                {
                    insurServer.failOutPay(new RequestHeader() { interfaceId = long.Parse(this.context.patientVm.interfaceId), alreadySelectDataList = this.context.alreadySelectDataList }, new OutPayFailRequest() { outPayMtNo = this.context.outPreSettlementResponse.settlementId.ToString(), patientId = this.context.patientVm.patientId, visitNo = this.context.outPreSettlementRequest.encounter.encounterId.ToString() });
                    this.context.chargingInfo.insurAmount = null;
                }
            }
            //医保预算取消
            if (this.context.preOutPayResponse != null)
            {
                try
                {
                    InsurServer insurServer = new InsurServer();
                    if (this.context.chargingInfo.settlementTypeCode == "1")
                    {
                        insurServer.cancelOutRegisterPreview(new RequestHeader() { interfaceId = long.Parse(this.context.patientVm.interfaceId), alreadySelectDataList = this.context.alreadySelectDataList }, new OutRegisterCancelPreviewRequest() { outPayMtNo = this.context.outPreSettlementResponse.settlementId.ToString(), patientId = this.context.patientVm.patientId, visitNo = this.context.outPreSettlementRequest.encounter.encounterId.ToString() });
                    }
                    else
                    {
                        insurServer.cancelOutPayPreview(new RequestHeader() { interfaceId = long.Parse(this.context.patientVm.interfaceId), alreadySelectDataList = this.context.alreadySelectDataList }, new OutPayCancelPreviewRequest() { outPayMtNo = this.context.outPreSettlementResponse.settlementId.ToString(), patientId = this.context.patientVm.patientId, visitNo = this.context.outPreSettlementRequest.encounter.encounterId.ToString() });
                    }
                    this.context.chargingInfo.insurAmount = null;
                }
                catch (Exception ex)
                {
                    MessageBox.Show("医保取消预算失败!" + ex.Message);
                }
            }
            NoticeChargeCancel?.Invoke(this, this.context);
        });

        /// <summary>
        /// 单据打印
        /// </summary>
        public void FormPrint(CashierContext context,FormPrintResp formPrintResp)
        {
            if (!formPrintResp.interfaceId.HasValue || formPrintResp.interfaceId == 0)
                return;

            
            if ("1".Equals(formPrintResp.formPrintRuleCoding))//通用设置
            {
                //询问开具
                if(formPrintResp.formPrintRuleXGeneral.formPrintCategoryCoding is 6)
                {
                    var messageBoxResult=MessageBox.Show("是否开具发票","询问",MessageBoxButton.YesNo, MessageBoxImage.Question,MessageBoxResult.No,MessageBoxOptions.ServiceNotification);
                    if (messageBoxResult != MessageBoxResult.Yes)
                        return;
                }
            }else if ("2".Equals(formPrintResp.formPrintRuleCoding))//按菜单设置
            {
                if (formPrintResp.formPrintRuleXMenuList == null || formPrintResp.formPrintRuleXMenuList.Count == 0)
                    return;
                var formPrintRuleXMenu=formPrintResp.formPrintRuleXMenuList.FirstOrDefault(f => f.menuID == context.menuId);
                if (formPrintRuleXMenu == null) return;
                if(formPrintRuleXMenu.formPrintCategoryCoding is 6)
                {
                    var messageBoxResult = MessageBox.Show("是否开具发票", "询问", MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.No, MessageBoxOptions.ServiceNotification);
                    if (messageBoxResult != MessageBoxResult.Yes)
                        return;
                }
            }
            if (!formPrintResp.interfaceId.HasValue || formPrintResp.interfaceId == 0)
                return;
            //开具发票
            InvoiceServer invoiceServer=new InvoiceServer();
            CurrentInvoiceRequest currentInvoiceRequest = new CurrentInvoiceRequest()
            {
                invoiceUsageCoding= context.outPreSettlementRequest.settlementTypeCode
            };
            var currentInvoiceResponses=invoiceServer.QueryCurrentInvoice(formPrintResp.interfaceId.Value, currentInvoiceRequest);

            var currentInvoiceResponse=currentInvoiceResponses.FirstOrDefault(f => f.invoiceTypeCoding == "2");

            if(currentInvoiceResponse == null) return;

            InvoiceIssueRequest invoiceIssueRequest = new InvoiceIssueRequest()
            {
                invoiceAllotId= currentInvoiceResponse.invoiceAllotId,
                invoiceUsageCoding= currentInvoiceRequest.invoiceUsageCoding,
                repairPrintFlag= "0",
                invoiceList=new List<InvoicingIndexRequest>()
                {
                    new InvoicingIndexRequest()
                    {
                        invoiceIndex="1",
                        invoiceAmt=context.chargeResult.recAmount,
                        hisBizIds=new List<string>{ context.chargeResult.settlementId.ToString() },
                    }
                }
            };

            invoiceServer.IssueInvoice(formPrintResp.interfaceId.Value, invoiceIssueRequest);
        }
    }
}
